package cn.smartfire.unit;

import android.annotation.SuppressLint;
import android.util.Log;

@SuppressLint("DefaultLocale")
public class Util {

	public static String toHexString(byte[] byteArray) {
		if (byteArray == null || byteArray.length < 1)
			throw new IllegalArgumentException(
					"this byteArray must not be null or empty");

		final StringBuilder hexString = new StringBuilder();
		for (int i = 0; i < byteArray.length; i++) {
			if ((byteArray[i] & 0xff) < 0x10)
				hexString.append("0");
			hexString.append(Integer.toHexString(0xFF & byteArray[i]));
			hexString.append(" ");
		}
		return hexString.toString().toLowerCase();
	}

	public static String toHexString(byte data) {
		StringBuilder hexString = new StringBuilder();
		if ((data & 0xff) < 0x10)
			hexString.append("0");
		hexString.append(Integer.toHexString(0xFF & data));
		return hexString.toString().toLowerCase();
	}

	public static byte toHexByte(String data) {
		return (byte) Integer.parseInt(data, 16);
	}

	public static byte[] toHexBytes(String data) {

		if (data == null) {
			return null;
		}
		byte[] result = new byte[data.length() / 2];
		try {
			for (int i = 0; i < result.length; i++) {
				result[i] = (byte) Integer.parseInt(
						data.substring(i * 2, i * 2 + 2), 16);
			}
		} catch (Exception e) {
			Log.e("Util", e.toString());
			return null;
		}
		return result;
	}
}
